/* global window */
import modelExtend from 'dva-model-extend'
import { config } from 'utils'
// 注意别和函数名重名。。。
import { query, info, createRole, remove, updateAuth } from 'services/auth'
import { query as menuSelect } from 'services/menu'
import { selection } from 'services/organization'

import { pageModel } from 'utils/model'

const { prefix } = config

export default modelExtend(pageModel, {
  namespace: 'auth',

  state: {
    currentItem: {},
    modalVisible: false,
    modalType: 'create',
    selectedRowKeys: [],
    treeData: [],
    treeCheckedKeys: [],
    isMotion: window.localStorage.getItem(`${prefix}userIsMotion`) === 'true',
    editingKey: '',
    treeSelectData: [],
    orgMenuList: [],
    roleName:'',
  },

  subscriptions: {
    setup({ dispatch, history }) {
      history.listen((location) => {
        if (location.pathname === '/app/auth') {
          dispatch({
            type: 'query',
            payload: location.query,
          })
        }
      })
    },
  },

  effects: {
    * query({ payload = {} }, { call, put }) {
      const data = yield call(query, payload)
      if (data.success) {
        yield put({
          type: 'querySuccess',
          payload: {
            list: data.page.list,
            pagination: {
              current: Number(payload.page) || 1,
              pageSize: Number(payload.pageSize) || 10,
              total: data.page.totalCount,
            },
          },
        })
      }
    },
    * queryKeyWords({ payload }, { call, put }) {
      const data = yield call(query, { ...payload })
      if (data.success) {
        yield put({
          type: 'editingKey',
          payload: {
            list: data.page.list,
            roleName:payload.roleName,
            pagination: {
              current: Number(payload.page) || 1,
              pageSize: Number(payload.pageSize) || 10,
              total: data.page.totalCount,
            },
          },
        })
      }
    },
    * changePage({ payload}, { call, put }) {
      const data = yield call(query, { page: payload.page, pageSize: payload.pageSize ,roleName:payload.roleName})
      if (data.success) {
        yield put({
          type: 'querySuccess',
          payload: {
            list: data.page.list,
            roleName:payload.roleName,
            pagination: {
              current: Number(payload.page) || 1,
              pageSize: Number(payload.pageSize) || 10,
              total: data.page.totalCount,
            },
          },
        })
      }
    },
    * delete({ payload }, { call, put }) {
      const data = yield call(remove, { roleIds: payload })
      if (data.success) {
        yield put({ type: 'query' })
      } else {
        throw data
      }
    },

    * multiDelete({ payload }, { call, put }) {
      const data = yield call(remove, payload)
      if (data.success) {
        yield put({ type: 'updateState', payload: { selectedRowKeys: [] } })
        yield put({ type: 'query' })
      } else {
        throw data
      }
    },

    

    * menuAuth({ payload }, { call, put }) {
      const data = yield call(menuSelect, payload)
      const organizationData = yield call(selection)
      if (data.success && organizationData.success) {
        let orgMenuList = []
        if (payload.modalType === 'update') {
          const auths = yield call(info, { roleId: payload.currentItem.roleId });
          console.log(auths);
          orgMenuList = auths.role.orgMenuList;
        }
        yield put({
          type: 'showModal',
          payload: {
            treeData: data.list,
            orgMenuList:orgMenuList,
            modalType: payload.modalType,
            currentItem: payload.currentItem ? payload.currentItem : '',
            treeSelectData: organizationData.organizationList
          },
        })
      } else {
        throw data
      }
    },
    * create({ payload }, { call, put }) {
      payload = {
        data: JSON.stringify(payload)
      }
      const data = yield call(createRole, payload)
      if (data.success) {
        yield put({ type: 'hideModal' })
        yield put({ type: 'query' })
      } else {
        throw data
      }
    },
    * update({ payload }, { call, put }) {
      payload = {
        data: JSON.stringify(payload)
      }
      const data = yield call(updateAuth, payload)
      if (data.success) {
        yield put({ type: 'hideModal' })
        yield put({ type: 'query' })
      } else {
        throw data
      }
    },

  },

  reducers: {

    showModal(state, { payload }) {
      return { ...state, ...payload, modalVisible: true }
    },

    hideModal(state) {
      return { ...state, modalVisible: false }
    },

    switchIsMotion(state) {
      window.localStorage.setItem(`${prefix}userIsMotion`, !state.isMotion)
      return { ...state, isMotion: !state.isMotion }
    },

    editingKey(state, { payload }) {
      return { ...state, ...payload }
    },
    updateOrgMenuListByOrg(state, { payload }) {
      const temp = state.orgMenuList.slice();
      for (let i in temp) {
        if (temp[i].organizationId === payload.organizationId) {
          temp[i] = payload;
          return { ...state, orgMenuList: temp };
        }
      }
      temp.push(payload);
      return { ...state, orgMenuList: temp }
    }
  },
})
